package com.niiwoo.civet.trade.service.local.newRefund.notify.dubbo;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.activity.stage.dto.request.prize.UseInterestRateReqDTO;
import com.niiwoo.activity.stage.dto.response.prize.UserPrizeResponseDTO;
import com.niiwoo.activity.stage.enums.prize.UserPrizeTypeIdEnum;
import com.niiwoo.activity.stage.enums.prize.UserPrizeUseSceneEnum;
import com.niiwoo.activity.stage.service.prize.ActivityPrizeDubboService;
import com.niiwoo.civet.base.enums.RefundTypeEnum;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestorPlan;
import com.niiwoo.civet.trade.dao.entity.RefundNotifyRecord;
import com.niiwoo.civet.trade.dao.entity.RefundOrder;
import com.niiwoo.civet.trade.dao.entity.RefundOrderDetailBiz;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestOrderMapper;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestorPlanMapperExt;
import com.niiwoo.civet.trade.dto.InvestReceiveAmountDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.RefundNotifyHandle;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyHandleResult;
import com.niiwoo.civet.trade.service.local.newRefund.notify.enums.RefundNotifyEnum;
import com.niiwoo.tripod.lanmao.enums.BusinessTypeEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * 活动中心-投资加息券事件
 * 
 * 触发条件：正常还款
 * 
 * @author: kevin.jia
 * @version 1.0.0
 */
@Slf4j
@Component
public class ActivityPrizeInvestRateNotify implements RefundNotifyHandle {
	
	@Autowired
	private ProjectInvestOrderMapper projectInvestOrderMapper;
	
	@Autowired
	private ProjectInvestorPlanMapperExt projectInvestorPlanMapper;
	
	@Reference(version = "1.0.0")
	private ActivityPrizeDubboService activityPrizeDubboService;

	@Override
	public RefundNotifyHandleResult handle(RefundNotifyDTO refundNotifyDTO) {
		RefundNotifyHandleResult refundNotifyHandleResult = null;
		try {
			UseInterestRateReqDTO useInterestRateReqDTO = (UseInterestRateReqDTO) bulidParam(refundNotifyDTO);
			if (useInterestRateReqDTO == null) return new RefundNotifyHandleResult();
			log.info("调用活动中心-投资加息券事件，RefundOrderId：{}, 请求参数：{}", refundNotifyDTO.getRefundOrder().getId(),
					JSONObject.toJSONString(useInterestRateReqDTO));
			activityPrizeDubboService.useInterestRatePrize(useInterestRateReqDTO);
			log.info("调用活动中心-投资加息券事件完成， RefundOrderId：{}", refundNotifyDTO.getRefundOrder().getId());
			refundNotifyHandleResult = new RefundNotifyHandleResult();
		} catch (Exception e) {
			refundNotifyHandleResult = new RefundNotifyHandleResult(e.getMessage());
			log.error("调用活动中心-投资加息券事件异常，异常原因：{}, 请求参数：{}", e.getMessage(), JSONObject.toJSONString(refundNotifyDTO.getRefundNotifyRecord()), e);
		}
		return refundNotifyHandleResult;
	}
	
	@Override
	public Object bulidParam(RefundNotifyDTO refundNotifyDTO) {
		RefundOrder refundOrder = refundNotifyDTO.getRefundOrder();
		RefundNotifyRecord refundNotifyRecord = refundNotifyDTO.getRefundNotifyRecord();
		List<RefundOrderDetailBiz> refundOrderDetailBizList = refundNotifyDTO.getRefundOrderDetailBizList();

    	ProjectInvestOrder projectInvestOrder = projectInvestOrderMapper.selectByPrimaryKey(refundNotifyRecord.getInvestOrderId());
    	
		// 调用活动中心查询红包，未查询到相关红包直接返回不处理
    	log.info("调用活动中心-查询红包信息，请求参数:UserId:{}, PrizeId:{}", projectInvestOrder.getUserId(), projectInvestOrder.getPrizeId());
		UserPrizeResponseDTO userPrizeResponseDTO = activityPrizeDubboService.getUserPrizeInfo(projectInvestOrder.getUserId(), projectInvestOrder.getPrizeId());
        if (userPrizeResponseDTO == null) {
        	log.info("调用活动中心-查询红包信息，没有查询到相关红包，UserId:{}, PrizeId:{}", projectInvestOrder.getUserId(), projectInvestOrder.getPrizeId());
        	return null;
        }
        log.info("调用活动中心-查询红包信息，返回结果:{}", JSONObject.toJSONString(userPrizeResponseDTO));

        // 判断是否投资加息红包，不是投资加息红包直接返回不处理
        if (!UserPrizeTypeIdEnum.INVESTMENT_RAISE_INTEREST_RATES.getPrizeType().equals(userPrizeResponseDTO.getPrizeTypeId())) {
        	return null;
        }
        
        // 汇总本次投资订单回款金额，回款金额为0时直接返回不处理
		InvestReceiveAmountDTO investReceiveAmountDTO = collectByInvestOrderIdForReceiveAmount(
				refundOrderDetailBizList, refundNotifyRecord.getInvestOrderId(), refundNotifyRecord.getCurrentPeriod());
		if (investReceiveAmountDTO.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
			return null;
		}
        
        // 构建请求
		UseInterestRateReqDTO useInterestRateReqDTO = new UseInterestRateReqDTO();
		useInterestRateReqDTO.setUserId(projectInvestOrder.getUserId());
		useInterestRateReqDTO.setPrizeId(projectInvestOrder.getPrizeId());
		useInterestRateReqDTO.setInvestOrderId(projectInvestOrder.getId());
		useInterestRateReqDTO.setCurrentPeriods(refundNotifyRecord.getCurrentPeriod());
		if (investReceiveAmountDTO.getInterest().compareTo(BigDecimal.ZERO) > 0) {
			useInterestRateReqDTO.setBackInterest(true);
		} else {
			useInterestRateReqDTO.setBackInterest(false);
		}
		if (RefundTypeEnum.OVERDEPT.getRefundType().equals(refundOrder.getRefundType())) {
			useInterestRateReqDTO.setUserPrizeUseSceneEnum(UserPrizeUseSceneEnum.REPAYMENT_ADVANCE);
		}
        return useInterestRateReqDTO;
	}
	
	/**
	 * 根据投资订单与期数汇总回款金额
	 * 
	 * @param refundOrderDetailBizList
	 * 				还款业务详情
	 * @param investOrderId
	 * 				投资订单ID
	 * @param currentPeriod
	 * 				期数
	 * @return
	 */
	private InvestReceiveAmountDTO collectByInvestOrderIdForReceiveAmount(
			List<RefundOrderDetailBiz> refundOrderDetailBizList, Long investOrderId, Integer currentPeriod) {
		InvestReceiveAmountDTO investReceiveAmountDTO = new InvestReceiveAmountDTO();
		investReceiveAmountDTO.setInvestOrderId(investOrderId);
		
		for (RefundOrderDetailBiz refundOrderDetailBiz : refundOrderDetailBizList) {
			// 回款金额小于0、期数不匹配的、非还款，代偿的直接跳过
			if (refundOrderDetailBiz.getAmount().compareTo(BigDecimal.ZERO) <= 0
					|| !refundOrderDetailBiz.getCurrentPeriod().equals(currentPeriod)
					|| (!BusinessTypeEnum.REPAYMENT.name().equals(refundOrderDetailBiz.getBizType()) && !BusinessTypeEnum.COMPENSATORY.name().equals(refundOrderDetailBiz.getBizType()))) {
				continue;
			}
			
			ProjectInvestorPlan projectInvestorPlan = projectInvestorPlanMapper.selectByPrimaryKey(refundOrderDetailBiz.getBackPlanId());
			if (null != projectInvestorPlan && investOrderId.equals(projectInvestorPlan.getInvestOrderId())) {
				if (null == investReceiveAmountDTO.getInvestorUserId()) {
					investReceiveAmountDTO.setInvestorUserId(refundOrderDetailBiz.getTargetUserId());
				}
				investReceiveAmountDTO.setTotalAmount(investReceiveAmountDTO.getTotalAmount().add(refundOrderDetailBiz.getAmount()));
				investReceiveAmountDTO.setCapital(investReceiveAmountDTO.getCapital().add(refundOrderDetailBiz.getCapital()));
				investReceiveAmountDTO.setInterest(investReceiveAmountDTO.getInterest().add(refundOrderDetailBiz.getInterest()));
				investReceiveAmountDTO.setPenaltyFee(investReceiveAmountDTO.getPenaltyFee().add(refundOrderDetailBiz.getPenaltyFee()));
			}
		}
		return investReceiveAmountDTO;
	}
	
	@Override
	public RefundNotifyEnum getType() {
		return RefundNotifyEnum.ACTIVITY_PRIZE_INVEST_RATE;
	}	
}